import {login, register} from "@/api/login";
import {Local} from "@/utils/local";
import {MittEventEnum} from "@/utils/enum/mitt-event-enum";
import {LoginStateEnum} from "@/utils/enum/enum";

import emitter from "@/utils/event-bus"
import {ElMessage, ElMessageBox} from "element-plus";


export function loginFunction(username, password) {
    var p = new Promise((resolve, reject) => {
        login(
            {
                username: username,
                password: password,
                grant_type: 'password',
            }
        ).then(response => {
            if (response['code'] == 200) {
                const {access_token, token_type} = response.data
                const accessToken = token_type + " " + access_token
                Local.setToken(accessToken);
                resolve(access_token)
                ElMessage({
                    showClose: true,
                    message: "登录成功 ~ ",
                    type: 'success',
                });
                emitter.emit(MittEventEnum.LOGIN_STATE_EVENT, LoginStateEnum.LOGINED)// 发送事件已经登陆
            } else {
                reject(response["msg"])
            }
        }).catch(error => {
            reject(error)
        })
    })
    return p;
}


export function registerFunction(account, password,verficationCode) {
    var p = new Promise((resolve, reject) => {
        register(
            {
                account: account,
                passwordCode: password,
                emailVerificationCode: verficationCode
            }
        ).then(response => {
            if (response['code'] == 200) {
                ElMessage({
                    showClose: true,
                    message: "注册成功 ~ ",
                    type: 'success',
                });
                const headTitle = response.data
                resolve(headTitle)
            } else {
                reject(response["msg"])
            }
        }).catch(error => {
            reject(error)
        })
    })
    return p;
}